package socket;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;

public class Http {
    Socket soc;
    String host;
    String URL;
    String path;
    OutputStream bos;
    BufferedInputStream bis;//输入流
    HashMap<String,String> headers;

    public void  counx(String url) throws IOException {
        int idx=url.indexOf('/');//返回字符"/"在字符串中第一次出现处的索引
        host=url.substring(0,idx);//括号里的是数组下标,返回一个新字符串，从0开始到idx为止的一个子字符串
        path=url.substring(idx);
        Socket soc=new Socket(host,80);
        bos=soc.getOutputStream();//获得此套接字的输出流
        bis=new BufferedInputStream(soc.getInputStream());//获得此套接字的输入流
        headers=new HashMap<>();
    }

    /**
     * 这下面是发出请求
     */
    public void dont() throws IOException {
        StringBuilder sb=new StringBuilder();
        sb.append("GET ").append(path ).append("HTTP/2.0").append("\r\n");

        sb.append("Host: ").append(host).append("\r\n");
        sb.append("Accept: ").append("*/*\r\n");
        sb.append("\r\n");
        bos.write(sb.toString().getBytes());
    }

    /**
     * 下面是读一行
     * @return
     * @throws IOException
     */
    public String readLine() throws IOException {
        StringBuilder stringBuilder=new StringBuilder();
        int ch;
        while((ch=bis.read())!=-1&&(ch!='\n')){
            stringBuilder.append((char)ch);
        }
        return stringBuilder.toString();
    }

    /**
     * 下面是应答
     */
    public void answer()throws IOException{
        String state=readLine();//状态行
        String line;//循环接收响应消息报头

        while (true){
            line=readLine();
            if (line==null || line.length()==0 )
            break;

             int x=line.indexOf(":");
             headers.put(line.substring(0,x),line.substring(x+2));

        }
        if(!headers.containsKey("Content-Length"))//该映射包含指定键的映射，返回true
            return;
        int length=Integer.parseInt(headers.get("Content-Length"));//该方法返回对应键对应的值

        int total=0;
              int  ch;
        FileOutputStream fi=new FileOutputStream("body.dat");//接收正文数据，将数据写入到文件body.dat
        while((total<=length)&&((ch=bis.read())!=-1)){
            fi.write(ch);
        }
        fi.close();
    }

    /**
     * 下面是关闭流
     */
    public void close() throws IOException {
        if (bis!=null)
            bis.close();
        if (bos!=null)
            bos.close();
        if (soc!=null)
            soc.close();
    }
    /**
     * 下面是测试方法
     */
    public static void main(String[] args) throws IOException {
        Http ht=new Http();
        ht.counx("mobile.weather.com.cn/data/forecast/101010100.html?_=1381891660081");
        ht.dont();
        ht.answer();
    }
}
